package com.liuguang.rabbitmq.config;

import com.alibaba.fastjson.JSON;
import com.liuguang.api.redis.RedisService;
import com.liuguang.common.constans.CommonConstans;
import com.liuguang.common.enums.RedisPreFixEnum;
import com.liuguang.rabbitmq.pojo.MyCorrelationData;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

/**
 * @ClassName: MyConfrimCallback
 * @Description：
 * @Author: wanghr
 * Date: 10:47 AM 2020/10/16
 * Version: 1.0
 */
@Component
public class MyConfrimCallback implements RabbitTemplate.ConfirmCallback {

    private static final Logger logger = LoggerFactory.getLogger(MyConfrimCallback.class);

    @DubboReference
    private RedisService redisService;

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        logger.info("回调接口：消息：{},是否被送到broker：{}", correlationData.getId(), ack);

        if (!ack) {
            if (correlationData instanceof MyCorrelationData) {
                MyCorrelationData myCorrelationData = (MyCorrelationData) correlationData;

                //消息发送失败，保存redis的list列表
                logger.info("消息发送broker失败，id：{}",myCorrelationData.getId());
                String key = CommonConstans.FAIL_MESSAGE_LIST_KEY;
                String value = JSON.toJSONString(correlationData);
                redisService.saveToList(key, value);
            }
        }

    }
}
